﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using ComicQ.Controller;
using ComicQ.Domain.Table;

namespace ComicQ.Dektop.View
{
    /// <summary>
    /// Interaction logic for WarrantyView.xaml
    /// </summary>
    public partial class WarrantyView
    {
        private readonly WarrantyController _warrantyControl;
        private IList<Warranty> _warranties;

        public WarrantyView()
        {
            InitializeComponent();

            _warrantyControl = new WarrantyController();
            _warranties = _warrantyControl.GetAllWarranty();
            dataGridWarranty.ItemsSource = _warranties;
        }

        private void RefreshGrid()
        {
            dataGridWarranty.ItemsSource = null;
            _warranties = _warrantyControl.GetAllWarranty();
            dataGridWarranty.ItemsSource = _warranties;
        }

        private void ButtonAddClick(object sender, RoutedEventArgs e)
        {
            var newWindow = new WarrantyEditorView();

            if (newWindow.ShowDialog() != false)
            {
            }
            else
            {
                RefreshGrid();
            }
        }

        private void ButtonDeleteClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridWarranty.SelectedItem == null)
                    throw new NullReferenceException();

                var warranty = _warranties
                        .Where(a => a.Id == _warranties[dataGridWarranty.SelectedIndex].Id)
                        .Select(a => a)
                        .Single();

                _warrantyControl.DeleteWarranty(warranty);
                MessageBox.Show("sukses menghapus warranty");
                RefreshGrid();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau didelete");
            }
        }

        private void ButtonEditClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridWarranty.SelectedItem == null)
                    throw new NullReferenceException();

                var newWindow = new WarrantyEditorView(_warranties[dataGridWarranty.SelectedIndex]);

                if (newWindow.ShowDialog() != false)
                {
                }
                else
                {
                    RefreshGrid();
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau diedit");
            }
        }
    }
}
